// pages/cart/cart.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    cartTotal: {
      "bookCount": 0,
      "bookAmount": 0.00,
      "checkedBookCount": 0,
      "checkedBookAmount": 0.00
    },
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    imgUrl: api.RootUrl,
  },

  getCartList: function () {
    let that = this;
    util.request(api.CartList).then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        that.setData({
          cartList: res.data.cartList,
          cartTotal: res.data.cartTotal,
          checkedAllStatus: false,
          isEditCart: false,
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },

  isCheckedAll: function () {
    //判断购物车商品已全选,every() 方法用于检测数组所有元素是否都符合指定条件（通过函数提供）。
    let that = this;
    console.log(that.data.cartList);
    return this.data.cartList.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  //单选按钮
  cartCheck: function (event) {
    let itemIndex = event.currentTarget.dataset.itemIndex;
    let that = this;
    console.log(that.data.cartList[itemIndex].checked);
    console.log("是不是选中了"+that.data.cartList[itemIndex].checked?0:1);
    if (!this.data.isEditCart) {
      util.request(api.CartChecked, { bookIds: that.data.cartList[itemIndex].bookId, isChecked: that.data.cartList[itemIndex].checked ? 0 : 1 }, 'POST').then(function (res) {
        if (res.errno === 0) {
          console.log(res.data);
          that.setData({
              cartList: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }
        console.log(that.data.cartList);

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartList.map(function (element, index, array) {
        if (index == itemIndex) {
          element.checked = !element.checked;
        }

        return element;
      });

      that.setData({
        cartList: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedBookCount': that.getCheckedGoodsCount(),
        'cartTotal.checkedBookAmount': that.getCheckedBookAmount(),
      });
    }
  },
  //全选按钮
  cartCheckAll: function () {
    let that = this;
    if (!this.data.isEditCart) {
      var bookIds = this.data.cartList.map(function (v) {
        return v.bookId;
      });
      console.log(bookIds);
      util.request(api.CartChecked, { bookIds: bookIds.join(','), isChecked: that.isCheckedAll() ? 0 : 1}, 'POST').then(function (res) {
        if (res.errno === 0) {
          console.log(res.data);
          that.setData({
            cartList: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }
        console.log(that.data.cartList);

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartList.map(function (v) {
        v.checked = !checkedAllStatus;
        return v;
      });

      that.setData({
        cartList: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount(),
        'cartTotal.checkedBookAmount': that.getCheckedBookAmount(),
      });
    }

  },

  getCheckedGoodsCount: function () {
    let checkedGoodsCount = 0;
    this.data.cartList.forEach(function (v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    console.log(checkedGoodsCount);
    return checkedGoodsCount;
  },

  getCheckedBookAmount: function () {
    let checkedBookAmount = 0;
    this.data.cartList.forEach(function (v) {
      if (v.checked === true) {
        checkedBookAmount += v.retailPrice*v.number;
      }
    });
    console.log(checkedBookAmount);
    return checkedBookAmount;
  },

  /* 修改 */
  cartEdit: function () {
    var page = this;
    var cartList = page.data.cartList;
    for (var i in cartList) {
      cartList[i].checked = false;
    }
    page.setData({
      cartList: cartList,
      isEditCart: true,
      checkedAllStatus: false,
    });

  },

  /* 完成 */
  cartDone: function () {
    var page = this;
    var cart_list = page.data.cart_list;
    for (var i in cart_list) {
      cart_list[i].checked = false;
    }
    page.setData({
      cart_list: cart_list,
      show_cart_edit: false,
      cart_check_all: false,
    });
    page.updateTotalPrice();
  },

  //数量减少1
  cutNumber: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartList[itemIndex];
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setData({
      cartList: this.data.cartList
    });
    this.updateCart(cartItem.bookId,cartItem.bookSpecifitionIds, number, cartItem.id);
  },
  //数量增加1
  addNumber: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartList[itemIndex];
    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setData({
        cartList: this.data.cartList
    });
    this.updateCart(cartItem.bookId, cartItem.bookSpecifitionIds, number, cartItem.id);
  },

  /*
    修改数量 
  */
  updateCart: function (bookId, bookSpecifitionIds,number, id) {
    let that = this;

    util.request(api.CartUpdate, {
      bookId: bookId,
      bookSpecifitionIds: bookSpecifitionIds,
      number: number,
      id: id
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        that.setData({
          //cartList: res.data.cartList,
          //cartTotal: res.data.cartTotal
        });
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });

  },

  /*
    删除 
  */
  deleteCart: function () {
    //获取已选择的商品
    let that = this;
    //根据选中过滤出有哪些选中要删除的（entity）
    let bookIds = this.data.cartList.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
    if (bookIds.length <= 0) {
      return false;
    }
    bookIds = bookIds.map(function (element, index, array) {
      if (element.checked == true) {
        return element.bookId;
      }
    });
    util.request(api.CartDelete, {
      bookIds: bookIds.join(',')
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        let cartList = res.data.cartList.map(v => {
          console.log(v);
          v.checked = false;
          return v;
        });

        that.setData({
          cartList: cartList,
          cartTotal: res.data.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },

  /*
    结算
  */
  cartSubmit: function () {
    var page = this;
    var cartList = page.data.cartList;
    var cartIdList = [];
    for (var i in cartList) {
      if (cartList[i].checked)
        cartIdList.push(cartList[i].id);
    }
    if (cartIdList.length == 0) {
      return true;
    }
    wx.navigateTo({
      url: '/pages/order-submit/order-submit?cartIdList=' + JSON.stringify(cartIdList),
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    that.setData({
      checkedAllStatus: false,
      isEditCart: false,
    });
    that.getCartList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})